import os
import cv2
import numpy as np


def find_one_from_dir(window, dir_path):
    icon_tags = os.listdir(dir_path)
    for tagName in icon_tags:
        file_path = dir_path + "/" + tagName

        flag, loc = is_icon_exist(window, file_path, (0, 0))
        if flag:
            return True, loc, tagName
    return False, (0, 0), None


def is_icon_exist(window, img_path, offset):
    """
    匹配界面icon
    """
    # 转换成灰度图，便于快速查找
    window_grey = cv2.cvtColor(window, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite("images/window_grey.jpeg", window_grey)

    # 获取图标图片
    icon_img = cv2.imread(img_path)
    icon_img_grey = cv2.cvtColor(icon_img, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite("images/icon_img_grey.jpeg", icon_img_grey)

    # 匹配界面
    match_result = cv2.matchTemplate(window_grey, icon_img_grey, cv2.TM_CCOEFF_NORMED)
    match_result_where = np.where(match_result >= 0.8)
    locations = list(zip(*match_result_where[::-1]))

    if len(locations) > 0:
        loc = (0, 0)
        for item in locations:
            if item[0] > 0 and item[1] > 0:
                loc = (item[0] + offset[0], item[1] + offset[1])
                return True, loc
    else:
        return False, (0, 0)
